package com.situ.servlet;

import com.alibaba.fastjson.JSON;
import com.situ.annotation.Param;
import com.situ.dto.PageEntity;
import com.situ.entity.Department;
import com.situ.service.IDepartmentService;
import com.situ.service.impl.DepartmentServiceImpl;
import com.situ.util.BaseServlet;
import com.situ.vo.ResultDataVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/dept")
public class DepartmentServlet extends BaseServlet {
    private static final long serialVersionUID = -5870352356676365313L;

    IDepartmentService deptService = new DepartmentServiceImpl();

    public void list(@Param("name") String name, PageEntity page, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Department> list = deptService.selectList(name, page);
        Integer sum = deptService.countDept(name);
        request.setAttribute("depts", list);
        request.setAttribute("sum", sum);
        request.setAttribute("page", page);
        request.getRequestDispatcher("/dept/list.jsp").forward(request, response);
    }

    public void asyncList(@Param("name") String name, PageEntity page, HttpServletResponse response) throws ServletException, IOException {
        List<Department> list = deptService.selectList(name, page);
        Integer sum = deptService.countDept(name);
        ResultDataVO vo = new ResultDataVO();
        vo.setCount(sum);
        vo.setData(list);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(vo));
    }

    public void save(Department dept, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (dept.getId() != null) {
            deptService.update(dept);
        } else {
            deptService.add(dept);
        }
        request.getRequestDispatcher("/dept/list.jsp").forward(request, response);
    }

    public void edit(@Param("id") Integer id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Department dept = deptService.selectById(id);
        request.setAttribute("dept", dept);
        request.getRequestDispatcher("/dept/add.jsp").forward(request, response);
    }

    public void del(@Param("id") Integer id) {
        deptService.delete(id);
    }

    public void all(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        List<Department> list = deptService.selectAll();
        response.getWriter().write(JSON.toJSONString(list));
    }
}
